<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/25 0025
 * Time: 16:21
 */

namespace app\api\controller;


use app\admin\model\Store;
use app\admin\model\Tenant;
use app\admin\model\Storeimg;
use app\common\BaseHelper;
use app\common\validate\IDMustBePostiveInt;

/**
 * Class TenantStore
 * @package app\api\controller
 * 商家店铺
 * 丁应清
 */
class TenantStore extends BaseController
{
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查找店铺信息
     */
    public function getStoreList()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能这空');
        } else {
            $tenantId = $param->tenantId;
            $storeList = Store::where('tenantId', $tenantId)->select();
            if (empty($storeList)) {
                return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到相关店铺信息');
            } else {
                for ($i = 0; $i < count($storeList); $i++) {
                    $storeImgs = Storeimg::where('storeId', $storeList[$i]->id)->select();
                    $storeList[$i]['img'] = $storeImgs;
                    $storeList[$i]['openWeek'] = '周'.str_replace('周','',$storeList[$i]['openWeek']);
                }
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $storeList);
            }
        }
    }

    /**
     * @param $tenantId
     * @param $lat
     * @param $lng
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取排好序的店铺列表
     */
    function getStoreSort()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能这空');
        } else if (empty($param->lng)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'lng不能这空');
        } else if (empty($param->lat)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'lat不能这空');
        } else {
            $tenantId = $param->tenantId;
            $lng = $param->lng;
            $lat = $param->lat;
            $storeList = $this->getStoreSortForDistance($tenantId, $lat, $lng);
            if ($storeList) {
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $storeList);
            } else {
                return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到相关店铺信息');
            }
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取距我最近的店铺
     */
    public function getNearbyStore()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能这空');
        } else if (empty($param->lng)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'lng不能这空');
        } else if (empty($param->lat)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'lat不能这空');
        } else {
            $tenantId = $param->tenantId;
            $lng = $param->lng;
            $lat = $param->lat;
            $storeList = $this->getStoreSortForDistance($tenantId, $lat, $lng);
            $isFacePayment = Tenant::where('id',$tenantId)->column('isFacePayment')[0];
            $storeList[0]['isFacePayment'] = $isFacePayment;

            if ($storeList) {
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $storeList[0]);
            } else {
                return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到相关店铺信息');
            }

        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 店铺按由近到远排序
     */
    function getStoreSortForDistance($tenantId, $lat, $lng,$wheredata = '',$storeName = '')
    {
        if($wheredata){
            if($storeName){
                $storeList = Store::where('tenantId', $tenantId)->where($wheredata)->where('name','like','%'.$storeName.'%')->select()->toArray();
            }else{
                $storeList = Store::where('tenantId', $tenantId)->where($wheredata)->select()->toArray();
            }
        }else{
            $storeList = Store::where('tenantId', $tenantId)->select()->toArray();
        }


        $stores = [];
        if (empty($storeList)) {
            return false;
        } else {
            for ($i = 0; $i < count($storeList); $i++) {
                $distance = $this->getDistance($lat, $lng, $storeList[$i]);
                if (!empty($distance)) {
                    $storeImgs = Storeimg::where('storeId', $storeList[$i]['id'])->select();
                    $storeList[$i]['img'] = $storeImgs;
                    $storeList[$i]['distance'] = $distance;
                    $storeList[$i]['openWeek'] = '周'.str_replace('周','',$storeList[$i]['openWeek']);
                    array_push($stores, $storeList[$i]);
                }

            }
            foreach ($stores as $k => $v) {
                $dos[$k] = $v['distance'];
            }
            array_multisort($dos, SORT_ASC, $stores);
            return $stores;
        }
    }

    /**
     * @param $lat
     * @param $lng
     * @param $store
     * @return float
     * 根据经续度获得与店铺间的距离,保留两位小数
     */
    function getDistance($lat, $lng, $store)
    {
        $site = explode(",", $store['addressGeo']);



        //将角度转为狐度
        $radLat1 = deg2rad($lat);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($site[0]);
        $radLng1 = deg2rad($lng);
        $radLng2 = deg2rad($site[1]);

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371.393 * 1000;
        //return round($s, 2);
        return sprintf("%.2f", $s);

            //200公里范围内
//        $url = sprintf(config('umap.URL'),$lat.','.$lng,$site[1].','.$site[0],config('baidumap.AK'));
//        $r2 = json_decode(BaseHelper::curlGet($url),true);
//        if($r2['status']==0){
//            return $r2['result'][0]['distance']['value'];
//        }

        //10公里范围内的
//        $r2 = json_decode(BaseHelper::curlGet("http://apis.map.qq.com/ws/distance/v1/?mode=walking&from=$lat,$lng&to=$site[0],$site[1]&key=XTXBZ-GMUCQ-3P454-GEY3S-VLQP2-CXB5B"));
//        if ($r2->status==0) {
//            return $r2->result->elements[0]->distance;
//        }
    }

    //店铺搜索
    public function searchStore(){
        //获取当前的省市区
        $searchArea = input('post.searchArea/a');
        $searchWord = input('post.searchWord','');
        $tenantId = input('post.tenantId');
        $lat = input('post.lat');
        $lng = input('post.lng');
        $wheredata['province'] = $searchArea[0];
        $wheredata['city'] = $searchArea[1];
        $wheredata['district'] = $searchArea[2];
        $storeName = '';
        if($searchWord){
            $storeName = $searchWord;
        }

        $storeList = $this->getStoreSortForDistance($tenantId,$lat,$lng,$wheredata,$storeName);
        if($storeList){
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $storeList);
        }else{
            return show(config('status.EMPTY_STATUS'), '没有找到店铺', '未查到相关店铺信息');
        }
    }

    //根据店铺id获取店铺详情
    public function getStoreDetails($id = ''){
        (new IDMustBePostiveInt())->goCheck();
        $Store = \app\common\model\Store::where('id',$id)->find();

        if($Store){
            $storeimgs = Storeimg::where('storeId',$Store->id)->select();
            $Store->img = $storeimgs;
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $Store);
        }else{
            return show(config('status.EMPTY_STATUS'), '没有找到店铺', '未查到相关店铺信息');
        }
    }


}